package com.jzsec.proxy.jzsecproxy.consumer;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.jzsec.proxy.jzsecproxy.services.LeancloudService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;

/**
 * redis command:
 * publish leancloud-req-topic "{\"reqHeader\":{\"X-LC-Id\":\"pYRbJzUEENH1FeOhwBzwBM4p-gzGzoHsz\",\"X-LC-Key\":\"3w9fEyL8I7neyP696MKRPw1j,master\",\"Content-Type\":\"application/json\"},\"reqBody\":{\"from_peer\":\"sys_secretary_001\",\"message\":{\"_lctype\":-1,\"_lctext\":\"This is a java msg for test24\",\"_lcattrs\":{\"content\":\"This is a java msg for test24\"}},\"conv_id\":\"569629a260b2a781fa1c768c\",\"transient\":false,\"to_peers\":[\"imaster_67987\"]},\"url\":\"https://leancloud.cn/1.1/rtm/messages\"}"
 */
@Component
@Slf4j
public class RedisMsgListener implements MessageListener {

	@Autowired
	private LeancloudService leancloudService;
	private ObjectMapper jsonMapper = new ObjectMapper();

	@Override
	public void onMessage(Message message, @Nullable byte[] bytes) {
		String msg = new String(message.getBody());
		log.info("msg = " + msg);
		try {
			leancloudService.sendMessageByOkHttp(msg);
		} catch (Exception e) {
			log.error(msg, e);
		}
	}
}

/*
在 Application 中 执行如下代码 可以执行 msg
	@Autowired
	private RedisConnectionFactory redisConnectionFactory;
	@Autowired
	private MessageListener redisMsgListener;
	@Autowired
	private ThreadPoolTaskScheduler taskScheduler;

	@Bean
	public ThreadPoolTaskScheduler initTaskScheduler() {
		if (null != taskScheduler) {
			return taskScheduler;
		}
		taskScheduler = new ThreadPoolTaskScheduler();
		taskScheduler.setPoolSize(20);
		return taskScheduler;
	}

	@Bean
	public RedisMessageListenerContainer initRedisContainer() {
		RedisMessageListenerContainer container = new RedisMessageListenerContainer();
		container.setConnectionFactory(redisConnectionFactory);
		container.setTaskExecutor(taskScheduler);
		Topic topic = new ChannelTopic("leancloud-req-topic");
		container.addMessageListener(redisMsgListener, topic);
		return container;
	}

 */